<?php
namespace app\admin\controller;

use think\Validate;
use zzcms\util\Tool;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupName;

/**
 * 权限分组管理
 * Class Authgroup
 * @package app\admin\controller
 * 说明：超管可创建默认套餐，但套餐中包含一个子账户，其他用户
 * 子账户可设置用户的权限（以子账户权限为最大权限），但不能设置自己的权限
 * 源ID为0时，则为超管和管理员新建的组
 */
class Authgroup extends Base
{
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = AuthGroupModel::getInstance();
    }

    public function lists()
    {
        $rule_cache = getTableCache('auth_rule');
        if ($this->admin_level == 1) {
            //套餐名字
            $auth_group_names = AuthGroupName::getInstance()->column('*', 'id');
            $lists = $this->model->paginate(20);
        } else {
            //套餐名字,子账号不包含管理账号
            $auth_group_names = AuthGroupName::getInstance()->whereIn('admin_id', "0,$this->admin_id")->where(['is_admin' => 0])->column('*', 'id');
            //管理员列表
            $lists = $this->model->where(['is_admin' => 0, 'creator_id' => $this->admin_id])->paginate(20);
        }
        foreach ($lists as $k => $item) {
            $rule_ids = explode(',', $item['rules']);
            $rule_str = '';
            foreach ($rule_ids as $rule_id) {
                $rule_str .= isset($rule_cache[$rule_id]) ? '<span>' . $rule_cache[$rule_id]['title'] . '；</span>' : '';
            }
            $item['titles'] = $rule_str;
            $item['role_name'] = isset($auth_group_names[$item['name_id']]) ? $auth_group_names[$item['name_id']]['name'] : '-';
            $lists[$k] = $item;
        }
        $this->assign('lists', $lists);
        return $this->fetch();
    }


    /**
     * 用户组添加
     */
    public function publish()
    {
        if (!$this->request->isPost()) {
            $this->error('非法操作2');
        }
        $post = $this->request->param();
        $validate = Validate::make([
            'title' => 'require',
            'rules' => 'require'
        ],
            [
                'title.require' => '套餐名称必须输入',
                'rules.require' => '请选择权限内容'
            ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        if ($this->admin_level > 3) {
            return $this->error('您无权限');
        }
        //添加权限套餐名字
        $data = [
            'name' => $post['title'],
            'is_admin' => $this->admin_level == 1 ? 1 : 0,
            'admin_id' => $this->admin_id,
            'status' => 1
        ];
        $add_id = AuthGroupName::getInstance()->addData($data);
        //添加权限套餐
        $post['name_id'] = $add_id;
        $post['is_admin'] = $this->admin_level == 1 ? 1 : 0;
        $post['creator_id'] = $this->admin_level == 1 ? 0 : $this->admin_id;
        if ($this->model->addData($post)) {
            $this->success('操作成功', url('lists'));
        } else {
            $this->error($this->model->getError());
        }
    }

    /**
     * 权限套餐修改
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $this->error('非法操作');
        }
        $post = $this->request->param();
        $id = isset($post['id']) ? intval($post['id']) : 0;
        if ($id < 1) {
            return $this->error('缺少ID');
        }
        $validate = Validate::make([
            'title' => 'require',
            'rules' => 'require'
        ],
            [
                'title.require' => '套餐名称必须输入',
                'rules.require' => '请选择权限内容'
            ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $info = $this->model->getOne($id);
        if (empty($info)) {
            return $this->error('暂无数据');
        }
        if (!($this->admin_level == 1 || $info['creator_id'] == $this->admin_id)) {
            return $this->error('您无权限');
        }
        //修改权限套餐名字
        $where = $this->admin_level == 1 ? ['id' => $info['name_id']] : ['id' => $info['name_id'], 'admin_id' => $this->admin_id];
        $result = AuthGroupName::getInstance()->where($where)->setField(['name' => $post['title']]);

        if (false === $result) {
            return $this->error(AuthGroupName::getInstance()->getError());
        }
        if ($this->model->editData($post)) {
            //返回数据，更新列表中对应的行
            $rule_ids = explode(',', $post['rules']);
            $rule_str = '';
            $rule_cache = getTableCache('auth_rule');
            foreach ($rule_ids as $rule_id) {
                $rule_str .= isset($rule_cache[$rule_id]) ? '<span>' . $rule_cache[$rule_id]['title'] . '；</span>' : '';
            }
            $post['rule_name'] = $rule_str;
            $post['create_time'] = $info['create_time'];
            $post['update_time'] = formatTime(time());
            $this->success('操作成功', url('lists'), $post);
        } else {
            $this->error($this->model->getError());
        }

    }

    /**
     * 删除权限套餐
     * @return mixed
     */
    public function delete()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 1) {
            return $this->error("ID非法！");
        }
        if ($this->model->deleteData($id)) {
            return $this->success("删除成功！");
        } else {
            return $this->error($this->model->getError());
        }
    }

    /**
     * 超管可以修改所有子账号及用户，
     */
    public function password()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();
            $admin_id = intval($post['id']);
            if ($admin_id < 1) {
                return $this->error('请指明要修改信息的用户');
            }
            if ($post['new_password'] != $post['new_pwdconfirm']) {
                return $this->error('两次输入密码不一样');
            }
            // 查询旧密码输入是否正确
            $info = $this->model->getOne($admin_id);
            if (empty($info)) {
                return $this->error('用户不存在');
            }
            if ($info['password'] != zzcmsPassword($post['old_password'], $info['password_code'])) {
                return $this->error('原始密码错误');
            }
            //判断其是否有权限
            if (!($info['founder'] == 1 || $this->admin_id == $admin_id || $info['parent_id'] == $admin_id || $info['status'] == 1)) {
                return $this->error('您无权限');
            }
            $data = ['id' => $admin_id];
            $data['password'] = zzcmsPassword($post['new_password'], $info['password_code']);
            if (false === $this->model->editData($data)) {
                return $this->error('修改信息错误');
            } else {
                return $this->success('修改成功');
            }
        } else {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if ($id < 1) {
                $id = $this->admin_id;
            }
            $this->assign($this->model->getOne($id));
            return $this->fetch();
        }
    }


    /**
     * 添加用户权限获取的字符串
     *
     *
     *
     * @return mixed
     */
    public function getRuleAdd()
    {
        //超管ID为1
        if ($this->admin_level > 2) {
            return $this->error('您无权限');
        }
        $rule_cache = getTableCache('auth_rule');
        $tree = Tool::createTree($rule_cache);
        //判断管理员的权限
        if ($this->admin_level != 1) {
            //获取管理员所拥有的权限
            $group_info = $this->model->getOne(['is_admin' => 1, 'creator_id' => $this->admin_id]);
            $allow_rule_ids = explode(',', $group_info['rules']);
        } else {
            $allow_rule_ids = array_keys($rule_cache);
        }
        $str = '';
        foreach ($tree as $item) {
            if (!in_array($item['id'], $allow_rule_ids)) {
                continue;
            }
            $is_child = isset($item['child']) ? true : false;
            $str .= '<div class="tree-one">';
            $str .= '    <div class="level-one">';
            if ($is_child) {
                $str .= '   <span class="tree-down"><i class="fa fa-caret-right"></i></span>';
            } else {
                $str .= '   <span class="tree-down"></span>';
            }
            $str .= '        <p class="tree-choose-one" data-id="' . $item['id'] . '"><i class="fa fa-check"></i></p>';
            $str .= '        <p class="tree-text">' . $item['title'] . '</p>';
            $str .= '    </div>';
            if ($is_child) {
                foreach ($item['child'] as $item2) {
                    if (!in_array($item2['id'], $allow_rule_ids)) {
                        continue;
                    }
                    $is_child2 = isset($item2['child']) ? true : false;
                    $str .= '    <div class="tree-two">';
                    $str .= '        <div class="level-two">';
                    if ($is_child2) {
                        $str .= '   <span class="tree-down"><i class="fa fa-caret-right"></i></span>';
                    } else {
                        $str .= '   <span class="tree-down"></span>';
                    }
                    $str .= '            <p class="tree-choose-one" data-id="' . $item2['id'] . '"><i class="fa fa-check"></i></p>';
                    $str .= '            <p class="tree-text">' . $item2['title'] . '</p>';
                    $str .= '        </div>';
                    if ($is_child2) {
                        $str .= '    <div class="tree-three">';
                        foreach ($item2['child'] as $item3) {
                            if (!in_array($item3['id'], $allow_rule_ids)) {
                                continue;
                            }
                            $str .= '        <div class="level-three">';
                            $str .= '            <span class="tree-down"></span>';
                            $str .= '            <p class="tree-choose-one" data-id="' . $item3['id'] . '"><i class="fa fa-check"></i></p>';
                            $str .= '            <p class="tree-text">' . $item3['title'] . '</p>';
                            $str .= '        </div>';
                        }
                        $str .= '    </div>';
                    }
                    $str .= '    </div>';
                }
            }
            $str .= '</div>';
        }
        return $this->success('ok', '', $str);
    }


    /**
     * 修改用户权限获取的字符串
     *
     *
     *
     * @return mixed
     */
    public function getRuleEdit()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 1) {
            return $this->error('no');
        }
        $info = $this->model->getOne($id);
        if (empty($info)) {
            return $this->error('暂无数据');
        }
        //超管ID为1
        if ($this->admin_level != 1 && $info['creator_id'] != $this->admin_id) {
            return $this->error('您无权限');
        }
        $rule_cache = getTableCache('auth_rule');
        //判断管理员的权限
        if ($this->admin_level != 1) {
            //获取管理员所拥有的权限
            $group_info = $this->model->getOne(['is_admin' => 1, 'creator_id' => $this->admin_id]);
            $allow_rule_ids = explode(',', $group_info['rules']);
        } else {
            $allow_rule_ids = array_keys($rule_cache);
        }
        $tree = Tool::createTree($rule_cache);
        $rule_array = explode(',', $info['rules']);
        $str = '';
        foreach ($tree as $item) {
            if (!in_array($item['id'], $allow_rule_ids)) {
                continue;
            }
            $is_child = isset($item['child']) ? true : false;
            $is_select = in_array($item['id'], $rule_array) ? 'power-tree-add' : '';
            $str .= '<div class="tree-one">';
            $str .= '    <div class="level-one">';
            if ($is_child) {
                $str .= '   <span class="tree-down"><i class="fa fa-caret-right"></i></span>';
            } else {
                $str .= '   <span class="tree-down"></span>';
            }
            $str .= '        <p class="tree-choose-one ' . $is_select . '" data-id="' . $item['id'] . '"><i class="fa fa-check"></i></p>';
            $str .= '        <p class="tree-text">' . $item['title'] . '</p>';
            $str .= '    </div>';
            if ($is_child) {
                foreach ($item['child'] as $item2) {
                    if (!in_array($item2['id'], $allow_rule_ids)) {
                        continue;
                    }
                    $is_child2 = isset($item2['child']) ? true : false;
                    $is_select2 = in_array($item2['id'], $rule_array) ? 'power-tree-add' : '';
                    $str .= '    <div class="tree-two">';
                    $str .= '        <div class="level-two">';
                    if ($is_child2) {
                        $str .= '   <span class="tree-down"><i class="fa fa-caret-right"></i></span>';
                    } else {
                        $str .= '   <span class="tree-down"></span>';
                    }
                    $str .= '            <p class="tree-choose-one ' . $is_select2 . '" data-id="' . $item2['id'] . '"><i class="fa fa-check"></i></p>';
                    $str .= '            <p class="tree-text">' . $item2['title'] . '</p>';
                    $str .= '        </div>';
                    if ($is_child2) {
                        $str .= '    <div class="tree-three">';
                        foreach ($item2['child'] as $item3) {
                            if (!in_array($item3['id'], $allow_rule_ids)) {
                                continue;
                            }
                            $is_select3 = in_array($item3['id'], $rule_array) ? 'power-tree-add' : '';
                            $str .= '        <div class="level-three">';
                            $str .= '            <span class="tree-down"></span>';
                            $str .= '            <p class="tree-choose-one ' . $is_select3 . '" data-id="' . $item3['id'] . '"><i class="fa fa-check"></i></p>';
                            $str .= '            <p class="tree-text">' . $item3['title'] . '</p>';
                            $str .= '        </div>';
                        }
                        $str .= '    </div>';
                    }
                    $str .= '    </div>';
                }
            }
            $str .= '</div>';
        }
        return $this->success('ok', '', $str);
    }


}